package com.huangguolin.cloud.mybatis.flexigrid;

import com.huangguolin.cloud.mybatis.annotation.Colums;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class PadingRstEntity<T> implements Serializable {

    private Logger log = LogManager.getLogger(PadingRstEntity.class);

    private Integer total;

    private Integer page;

    private List<PageRowsEntity> rows = new ArrayList<PageRowsEntity>();

    private List<String> columns = new ArrayList<>();

    private List<T> rawRecords;

    public Integer getTotal() {
        return total;
    }

    public void setTotal(Integer total) {
        this.total = total;
    }

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public List<PageRowsEntity> getRows() {
        return rows;
    }

    public void setRows(List<PageRowsEntity> rows) {
        this.rows = rows;
    }

    public List<String> getColumns() {
        return columns;
    }

    public void setColumns(List<String> columns) {
        this.columns = columns;
    }

    public List<T> getRawRecords() {
        return rawRecords;
    }

    public void setRawRecords(List<T> rawRecords) {
        this.rawRecords = rawRecords;
    }

    @Override
    public String toString() {
        return "PadingRstEntity{" +
                "log=" + log +
                ", total=" + total +
                ", page=" + page +
                ", rows=" + rows +
                ", columns=" + columns +
                ", rawRecords=" + rawRecords +
                '}';
    }

    public void putItem(){
        if(rawRecords == null || rawRecords.size() == 0){
            return;
        }
        Class<?> tClass = rawRecords.get(0).getClass();
        Field[] fields = tClass.getDeclaredFields();
        for(Field field:fields){
            if(field.isAnnotationPresent(Colums.class)){
                columns.add(field.getName());
            }
        }

        T item = null;
        PageRowsEntity pageRowsEntity = null;
        for (int i = 0;i < rawRecords.size();i++){
            item = rawRecords.get(i);
            pageRowsEntity = new PageRowsEntity();
            this.rows.add(pageRowsEntity);
            pageRowsEntity.setId(i);
            for(Field field:fields){
                if(field.isAnnotationPresent(Colums.class)){
                    field.setAccessible(true);
                    try {
                        pageRowsEntity.addCell(field.get(item));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }

        }


    }
}
